package com.blb.network;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 聊天服务器
 */
public class ChatServer {

    public static final int PORT = 8888;

    public void start(){
        System.out.println("启动聊天服务器");
        //创建线程池
        int cpuNum = Runtime.getRuntime().availableProcessors() * 2;
        ExecutorService threadPool = new ThreadPoolExecutor(cpuNum,cpuNum,0, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>());
        //创建ServerSocket
        try(ServerSocket serverSocket = new ServerSocket(PORT)){
            while(true){
                //接收客户端
                Socket client = serverSocket.accept();
                //启动读和写的线程
                threadPool.execute(new ReadRunnable(client));
                threadPool.execute(new WriteRunnable(client));
            }
        }catch (IOException ex){
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new ChatServer().start();
    }
}
